package cn.itcast.order.web;

import cn.itcast.order.common.ResponseResult;
import cn.itcast.order.common.ResultCode;
import cn.itcast.order.param.OrderAddParam;
import cn.itcast.order.pojo.Order;
import cn.itcast.order.service.OrderService;
import cn.itcast.order.util.JwtUtil;
import cn.itcast.usercontext.interceptor.LoginCheck;
import cn.itcast.usercontext.interceptor.NoLoginCheck;
import cn.itcast.usercontext.util.usersession.UserContext;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.util.List;

import static cn.itcast.order.common.ApiConstants.ORDER_PREFIX;

@RestController
@RequestMapping(ORDER_PREFIX)
@LoginCheck
public class OrderController {

    @Autowired
    private OrderService orderService;


    @GetMapping("{orderId}")
    @NoLoginCheck
    public Order queryOrderByUserId(@PathVariable("orderId") Long orderId) {
        // 根据id查询订单并返回
        return orderService.queryOrderById(orderId);
    }

    @PostMapping
    public ResponseResult createOrder(@RequestBody OrderAddParam order) {
        Order orderInsert = new Order();
        BeanUtils.copyProperties(order,orderInsert);
        if(UserContext.get() == null) {
            return ResponseResult.error("未登录！");
        }
        orderInsert.setUserId(UserContext.get().id.toString());

        Long orderId = orderService.create(orderInsert);
        return ResponseResult.success(orderId);
    }

    /**
     * 获取当前登录用户的订单信息
     */
    @ApiOperation("订单获取")
    @GetMapping
    public ResponseResult getOrderList(HttpServletRequest request) {
        LambdaQueryWrapper<Order> queryWrapper = new QueryWrapper<Order>().lambda();
        queryWrapper.eq(Order::getUserId, UserContext.get().id);
        List<Order> objects = orderService.list(queryWrapper);
        return new ResponseResult(ResultCode.SUCCESS.getCode(), "订单列表获取成功", objects);
    }
}
